using Microsoft.AspNetCore.Mvc;
using SheLife.Application.Services;
using SheLife.Domain.Entities;

namespace SheLife.AdminApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class HabitsController : ControllerBase
    {
        private readonly IHabitService _habitService;

        public HabitsController(IHabitService habitService)
        {
            _habitService = habitService;
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> GetHabitById(int id)
        {
            var habit = await _habitService.GetHabitByIdAsync(id);
            if (habit == null)
            {
                return NotFound();
            }
            return Ok(habit);
        }

        [HttpGet("user/{userId}")]
        public async Task<IActionResult> GetHabitsByUserId(int userId)
        {
            var habits = await _habitService.GetHabitsByUserIdAsync(userId);
            return Ok(habits);
        }

        [HttpGet("user/{userId}/category/{category}")]
        public async Task<IActionResult> GetHabitsByUserIdAndCategory(int userId, string category)
        {
            var habits = await _habitService.GetHabitsByUserIdAndCategoryAsync(userId, category);
            return Ok(habits);
        }

        [HttpGet("user/{userId}/active")]
        public async Task<IActionResult> GetActiveHabitsByUserId(int userId)
        {
            var habits = await _habitService.GetActiveHabitsByUserIdAsync(userId);
            return Ok(habits);
        }

        [HttpPost]
        public async Task<IActionResult> CreateHabit([FromBody] Habit habit)
        {
            var createdHabit = await _habitService.CreateHabitAsync(habit);
            return CreatedAtAction(nameof(GetHabitById), new { id = createdHabit.Id }, createdHabit);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateHabit(int id, [FromBody] Habit habit)
        {
            if (id != habit.Id)
            {
                return BadRequest();
            }

            var updatedHabit = await _habitService.UpdateHabitAsync(habit);
            if (updatedHabit == null)
            {
                return NotFound();
            }
            return Ok(updatedHabit);
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteHabit(int id)
        {
            var result = await _habitService.DeleteHabitAsync(id);
            if (!result)
            {
                return NotFound();
            }
            return NoContent();
        }
    }
}